﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SimpleUnitity.Cache
{
    using SimpleUnitity.Threading;
    public sealed class DynamicCache : WarpCache, ICache
    {
        public DynamicCache(int cacheTimeoutSeconds)
            : base(new NormalCache())
        {
            this.timeout = cacheTimeoutSeconds;
        }

        ICache callerCache = new NormalCache();
        private readonly int timeout;

        public override void Set(string key, object value)
        {
            base.Set(key, value);
            var caller = new DelayCaller();
            caller.OnTimeout += (sender, e) => this.Remove(key);
            caller.Delay(timeout);
            callerCache.Set(key, caller);
        }

        public override object Get(string key, object defaultValue = null)
        {
            var caller = callerCache.Get(key) as DelayCaller;
            if (caller != null)
            {
                caller.Delay(timeout);
            }
            return base.Get(key, defaultValue);
        }

        public override void Remove(string key)
        {
            var caller = callerCache.Get(key) as DelayCaller;
            if (caller != null)
            {
                callerCache.Remove(key);
                caller.Reset();
            }
            base.Remove(key);
        }
    }
}
